package com.atguigu.threadcorrespondence;

/**
 * 回顾线程间通信
 * wait()/notifu()/notifyAll()  -> 必虚在有锁的环境下使用
 */
class PrintAlternately {
    private int number = 1;
    private char letter = 'A';
    private final Object lock = new Object();
    private boolean printNumber = true;

    public void printNumber() {
        synchronized (lock) {
            while (number <= 52) {
                if (!printNumber) {
                    try {
                        lock.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                if (number <= 52) {
                    System.out.print(number++);
                    System.out.print(number++);
                    printNumber = false;
                    lock.notify();
                }
            }
        }
    }

    public void printLetter() {
        synchronized (lock) {
            while (letter <= 'Z') {
                if (printNumber) {
                    try {
                        lock.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                if (letter <= 'Z') {
                    System.out.print(letter++);
                    printNumber = true;
                    lock.notify();
                }
            }
        }
    }
}
public class Correspondence {
public static void main(String[] args) {
            PrintAlternately p = new PrintAlternately();

            new Thread(new Runnable() {
                @Override
                public void run() {
                    p.printNumber();

                }
            }, "A").start();

            new Thread(new Runnable() {
                @Override
                public void run() {
                    p.printLetter();
                }
            }, "B").start();

        }
    }



